<template>
  <div v-if="isOpen && !isChildModalOpen" class="edit-modal-overlay fixed inset-0 bg-black/50 z-50 flex items-center justify-center p-4">
    <div class="edit-modal-container w-full max-w-2xl max-h-[90vh] bg-white rounded-lg shadow-xl flex flex-col animate-fade-in">
      <!-- 弹窗头部 -->
      <div class="modal-header p-4 border-b flex justify-between items-center">
        <h3 class="text-lg font-semibold">{{ isArray ? '编辑数组' : '编辑对象' }}</h3>
        <button 
          class="text-gray-500 hover:text-gray-700 p-1" 
          @click="closeModal"
          title="关闭"
        >
          <i class="fa fa-times"></i>
        </button>
      </div>

      <!-- 弹窗内容 -->
      <div class="modal-body flex-1 overflow-y-auto p-4">
        <!-- 基本信息 -->
        <div class="mb-4">
          <div class="text-sm text-gray-500 mb-2">
            {{ isArray ? `共 ${elementCount} 个元素` : `共 ${propertyCount} 个属性` }}
          </div>
        </div>

        <!-- 使用第三方JSON编辑器 -->
        <div class="mb-4">
          <Vue3JsonEditor
            v-model="jsonData"
            :disabled="false"
            :mode="'form'"
            :expandedOnStart="true"
            @json-change="handleJsonChange"
            @json-error="handleJsonError"
            style="height: 400px;"
          />
        </div>
      </div>

      <!-- 弹窗底部 -->
      <div class="modal-footer p-4 border-t flex justify-end gap-2">
        <button 
          class="px-4 py-2 border border-gray-300 rounded hover:bg-gray-50 text-sm transition-colors"
          @click="closeModal"
        >
          取消
        </button>
        <button 
          class="px-4 py-2 bg-primary text-white rounded hover:bg-primary/90 text-sm transition-colors"
          @click="confirmChanges"
          :disabled="hasError"
        >
          确认
        </button>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, watch, computed } from 'vue';
import { Vue3JsonEditor } from 'vue3-json-editor';

export default {
  name: 'ThirdPartyJsonEditor',
  components: {
    Vue3JsonEditor
  },
  props: {
    isOpen: {
      type: Boolean,
      default: false
    },
    value: {
      type: [Array, Object],
      default: null
    },
    isChildModalOpen: {
      type: Boolean,
      default: false
    }
  },
  emits: ['close', 'confirm', 'update:isChildModalOpen'],
  setup(props, { emit }) {
    // 内部JSON数据
    const jsonData = ref(null);
    // 错误状态
    const hasError = ref(false);
    // 错误信息
    const errorMessage = ref('');
    // 是否是数组类型
    const isArray = computed(() => Array.isArray(jsonData.value));
    // 元素数量（数组）
    const elementCount = computed(() => {
      if (isArray.value && jsonData.value) {
        return jsonData.value.length;
      }
      return 0;
    });
    // 属性数量（对象）
    const propertyCount = computed(() => {
      if (!isArray.value && jsonData.value && typeof jsonData.value === 'object') {
        return Object.keys(jsonData.value).length;
      }
      return 0;
    });

    // 监听外部值变化，同步到本地副本
    watch(
      () => props.value,
      (newVal) => {
        // 深拷贝避免直接修改外部数据
        try {
          jsonData.value = JSON.parse(JSON.stringify(newVal || (Array.isArray(newVal) ? [] : {})));
          hasError.value = false;
          errorMessage.value = '';
        } catch (e) {
          console.error('数据初始化错误:', e);
          hasError.value = true;
          errorMessage.value = '数据格式错误';
        }
      },
      { deep: true, immediate: true }
    );

    // 监听打开状态变化
    watch(
      () => props.isOpen,
      (newVal) => {
        if (newVal) {
          // 打开时同步最新值
          try {
            jsonData.value = JSON.parse(JSON.stringify(props.value || (Array.isArray(props.value) ? [] : {})));
            hasError.value = false;
            errorMessage.value = '';
            // 处理模态框层级
            handleModalHierarchy();
          } catch (e) {
            console.error('数据初始化错误:', e);
            hasError.value = true;
            errorMessage.value = '数据格式错误';
          }
        }
      }
    );

    // 处理模态框层级关系
    const handleModalHierarchy = () => {
      // 记录当前模态框信息
      if (window.__currentModal) {
        // 如果已经有打开的模态框，记录为父模态框
        window.__parentModal = window.__currentModal;
        // 隐藏父模态框
        if (window.__parentModal && window.__parentModal.isOpen) {
          emit('update:isChildModalOpen', true);
        }
      }
      // 设置当前模态框为自己
      window.__currentModal = this;
    };

    // 处理JSON变化
    const handleJsonChange = (value) => {
      try {
        jsonData.value = value;
        hasError.value = false;
        errorMessage.value = '';
      } catch (e) {
        console.error('JSON解析错误:', e);
        hasError.value = true;
        errorMessage.value = e.message;
      }
    };

    // 处理JSON错误
    const handleJsonError = (error) => {
      console.error('JSON编辑器错误:', error);
      hasError.value = true;
      errorMessage.value = error;
    };

    // 关闭模态框
    const closeModal = () => {
      emit('close');
      // 如果有父级弹窗，通知父级可以显示
      if (window.__parentModal) {
        emit('update:isChildModalOpen', false);
      }
      // 清理父级弹窗引用
      if (window.__currentModal === this) {
        window.__currentModal = window.__parentModal;
        window.__parentModal = null;
      }
    };

    // 确认更改
    const confirmChanges = () => {
      if (hasError.value) return;
      
      // 确保返回正确的类型
      const result = jsonData.value || (Array.isArray(props.value) ? [] : {});
      
      emit('confirm', result);
      closeModal();
    };

    return {
      jsonData,
      hasError,
      errorMessage,
      isArray,
      elementCount,
      propertyCount,
      handleJsonChange,
      handleJsonError,
      closeModal,
      confirmChanges
    };
  }
};
</script>

<style scoped>
/* 动画效果 */
.animate-fade-in {
  animation: fadeIn 0.2s ease-out;
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(-10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

/* 覆盖第三方编辑器的样式以适应模态框 */
:deep(.vue3-json-editor) {
  border: 1px solid #e2e8f0;
  border-radius: 0.375rem;
}

:deep(.vue3-json-editor .jsoneditor-menu) {
  border-bottom: 1px solid #e2e8f0;
  background-color: #f8fafc;
}

:deep(.vue3-json-editor .jsoneditor) {
  border: none;
}

:deep(.vue3-json-editor textarea.jsoneditor-text) {
  font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
}
</style>